package org.zoomdev.zoom.rpc.client;

import java.io.IOException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.Function;

final class Completer {

    public byte[] bytes;
    public int id;
    public short func;

    private final int timeoutMs;

    boolean done;

    SimpleHandler handler;

    public Completer(int timeoutMs) {
        this.timeoutMs = timeoutMs;
    }


    public void setException(Throwable e) {
        future.completeExceptionally(e);
    }

    public void setResult(Object value) {
        future.complete(value);
    }

    public void then(Function function) {
        future.thenApply(function);
    }

    public boolean isDone() {
        return done;
    }

    private final CompletableFuture future = new CompletableFuture();


    public Object get() throws Throwable {
        try {
            return future.get(timeoutMs, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            throw new IOException("rpc执行中断");
        } catch (ExecutionException e) {
            throw e.getCause();
        } catch (TimeoutException e) {
            throw new IOException("rpc执行超时");
        } finally {
            done = true;
        }
    }
}
